<template>
  <render v-bind="props"></render>
</template>
<script setup lang="ts">
import { h, computed, VNode } from 'vue'
import { setObjectProperty } from '../util'
type PROPS = {
  type: string
  text: string
  url: string
  tag: string
  customStyle: Record<string, any>
  rid?: string
}
const props = withDefaults(defineProps<PROPS>(), {
  tag: 'span',
  customStyle: () => ({}),
})
const isLink = computed(() => {
  return 'a' === props.tag
})
const iconID = computed(() => {
  let _id = ''
  switch (props.type) {
    case 'link':
      _id = 'BDC/chain_link_line/1'
      break
    default:
      break
  }
  return _id
})
const iconSize = computed(() => {
  return 1.3 * ((props.customStyle.font_size as number) || 20)
})
const fontSize = computed(() => {
  return `${props.customStyle.font_size || 17}px`
})
const bold = computed(() => {
  return props.customStyle.bold
})
const italic = computed(() => {
  return props.customStyle.italic
})
const strikethrough = computed(() => {
  return props.customStyle.strikethrough
})

const createRichTextElement = (
  list: string[],
  params: Object,
  words: string
) => {
  let i: VNode | null = null
  let tagList: string[] = list?.length ? list : ['a']
  let text: string | undefined = words || undefined
  while (tagList.length) {
    let tag = tagList.pop()!
    if (i) {
      i = h(tag, tagList.length ? {} : params, [i])
    } else if (!tagList.length) {
      i = h(tag, params, text)
    } else {
      i = h(tag, {}, text)
    }
  }
  return i
}

const render = (props: PROPS) => {
  const { type, text, url, rid } = props
  const tagList = ['a']
  bold.value && tagList.push('strong')
  strikethrough.value && tagList.push('s')
  italic.value && tagList.push('i')
  //缺少链接前的图标
  return createRichTextElement(
    tagList,
    Object.assign(
      {
        class: setObjectProperty({ 'opus-text-rich-hl': true }, type, !!type),
        href: isLink.value ? url : undefined,
        target: isLink.value ? '_blank' : undefined,
        style: { fontSize: fontSize.value },
        directives: [],
      },
      isLink.value
        ? {}
        : {
            'data-rid': rid,
            'data-type': type,
          }
    ),
    text
  )
}
</script>
<style lang="scss" scoped></style>
